package com.yes.yll.servlet;

import com.yes.yll.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(urlPatterns = "/ylllogin")
public class login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("u");
        // 使用 Request 的 getParameter 方法获取查询字符串中键为 p 的值
        String password = req.getParameter("p");

        System.out.println("username = " + username);
        System.out.println("password = " + password);

        String code = req.getParameter("c");
        HttpSession session = req.getSession();
        Object yll = session.getAttribute("Yll");




        boolean isTrue = code != null && code.equals(yll);
        if(!isTrue){
            //输入的验证码不一致
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.write("验证码错啦！！！");
            writer.flush();
            writer.close();
            return;
        }
        String sql = "SELECT id FROM `user` WHERE username = ? AND `password` = MD5(?)";
        Integer id = JdbcUtils.select(sql, Integer.class, username, password);
        if(id!=null && id>0) {
            //成功查询到账号密码时，将其存储到session中。
            session.setAttribute("UID",id);
            //重定向到首页
            resp.sendRedirect("/yll/index.jsp");

        }else{
            //重定向到登录页
            resp.sendRedirect("/yll/Login.jsp");
        }

/*

        String message = id!=null && id>0? "登录成功！":"账号或密码错误，请重新输入！";
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write(message);
        writer.flush();
        writer.close();
*/

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
